package study.reactive.springboot.webflux.support.route;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RequestPredicate;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import study.reactive.springboot.webflux.handler.EchoHandler;

import java.util.Map;

@Slf4j
@Configuration
public class RoutingConfig implements ApplicationContextAware {

    private ApplicationContext ctx;

    @Bean
    public RouterFunction<ServerResponse> router(EchoHandler echoHandler) {
        t();
        //
        RequestPredicate predicate = RequestPredicates.accept(MediaType.APPLICATION_JSON)
                .and(RequestPredicates.GET("/ECHO/"));
        //
//        RouterFunction f = request ->  echoHandler.getAllUser(request);
        return RouterFunctions.route(predicate,
                echoHandler::getAllUser);
    }

    public void t() {
        Map<String, Object> d = ctx.getBeansWithAnnotation(Api.class);
        d.entrySet().stream().forEach(e -> {
            log.info("{}= {}", e.getKey(), e.getValue());

        });
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx = applicationContext;
    }
}
